<?php
/**
 * Created by PhpStorm.
 * User: jojo
 * Date: 6/2/2015
 * Time: 6:38 PM
 */

/**
 * C微信(或易信)公共平台处理类
 */

include_once __DIR__ .'/hermes.BusinessObject.php';
/**
 * Class C微信
 */
class CTo微信
{
    public $isTest = false;
    public $serv_id =G_SERV_ID;
    protected $accessToken = null;
    //当前用户openid
    protected  $userOpenId ;
    //当前公众号openid
    protected $gzhOpenId ;
    protected $vo信息中心;
    private $appToken = ""; // TOKEN值 此外系统中还有一个 access token 要注意区分
    // private $articles = array();
    private $appId ;
    private $appSecret ;




    /**
     * 检查签名是否正确
     * @param $signature
     * @param $timestamp
     * @param $nonce
     * @param string $appToken
     * @return boolean 正确返回true,否则返回false
     */
    public static function f验证签名($signature, $timestamp, $nonce,$公众号Id)
    {
        $token = 'errtoken找不到公众号id';
        /*        if (!empty($appid)) {
                $do公众号 = new DoPublic_serv_accounts();
                $do公众号->set_id($appid);
                $do公众号->loadByKeys($do公众号->data);
                $token = $do公众号->get_token();
                }
        */
        global $G_CONFIG;
        $token = $G_CONFIG['公众号信息'][$公众号Id]['公众号Token'];

        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }





    public static function ff发送文本消息($messageTxt, $toUserOpenID, $vs公众号id )
    {
        $msg = new DoMessage();
        $msg->set_content($messageTxt);
        $msg->set_message_type('text') ;
        $msg->set_to_user_name($toUserOpenID);


        return self::ff发送消息($msg,$toUserOpenID,$vs公众号id);
    }
    public static function ff发送消息_多类型(C返回信息多类型 $vo返回信息, $toUserOpenID, $vs公众号id )
    {
        $msg = new DoMessage();
        $msg->set_message_type($vo返回信息->get消息类型()) ;
        if($vo返回信息->get消息类型() =='image'){
            $msg->set_media_id($vo返回信息->getmedia_id());
            $msg->set_pic_url($vo返回信息->getPicUrl());
        }else if($vo返回信息->get消息类型() =='voice'){
            $msg->set_content($vo返回信息->get消息内容());
            $msg->set_media_id($vo返回信息->getmedia_id());
            $msg->set_format($vo返回信息->getFormat());
        }else if($vo返回信息->get消息类型() =='video'){
            $msg->set_media_id($vo返回信息->getmedia_id());
            $msg->set_thumb_media_id($vo返回信息->getThumbMediaId());
        }else{
            $msg->set_content($vo返回信息->get消息内容());
        }

        $msg->set_to_user_name($toUserOpenID);

        return self::ff发送消息($msg,$toUserOpenID,$vs公众号id);
    }



    public static  function ff发送图文消息( Cbo图文消息列表 $articles, $toUserOpenID, $vs公众号id )
    {
        $msg = new DoMessage();
        $msg->set_message_type('news');

        $msg->set_to_user_name($toUserOpenID);
        $n ='"articles": [';
        $i = 0;
        foreach ($articles->va消息列表 as $art) {
            $i++;
            if ($i > 1) $n .= ',';
            $n .= '{';
            $n .= '"title":"' . $art['标题'] . '",';
            $n .= '"description":"' . $art['描述'] . '",';
            $n .= '"picurl":"' . $art['图片链接'] . '",';
            $n .= '"url":"' . $art['页面链接'] . '"';
            $n .= '}';

        }
        $n .= ']';
        $msg->set_news($n);

        return self::ff发送消息($msg,$toUserOpenID, $vs公众号id );
    }
    public static function ff发送消息(DoMessage $message,$vs用户openId,$vs公众号id)
    {
        if(empty($vs用户openId))
            $toUserID = $message->get_to_user_name();
        else{
            $toUserID=$vs用户openId;
        }


        $messageType=$message->get_message_type();
        $content=$message->get_content();
        $info = '[' . $messageType . ']' .$content ;
        logger()->logInfo("---send Client MSG [msg]:" . $info . "[User]:" . $toUserID);
        $公众号accToken =  Tools::fh通过公众号id获取公众号Token信息($vs公众号id);


        //if()

        switch ($messageType) {
            case 'text':
                $cont = '{
                "touser": "' . $toUserID . '",
                "msgtype": "text",
                "text": {
                    "content": "' . $content . '"
                }
                }';

                break;
            case 'image':
                $cont = '{
                "touser": "' . $toUserID . '",
                "msgtype": "image",
                "image": {
                    "media_id": "' . $message->get_media_id() . '"
                }
                }';

                break;
            case 'voice':
                $公众号ID = pdo()->selectColumns('用户',array('公众号ID'),array('openID'=>$message->get_to_user_name()));
                if($公众号ID['公众号ID'] == $vs公众号id) {
                    $media_id = $message->get_media_id();
                }else {
                    $media_id = self::fh获取媒体资源media_id($message,$vs公众号id);
                }
                $cont = '{
                "touser": "' . $toUserID . '",
                "msgtype": "voice",
                "voice": {
                    "media_id": "' . $media_id . '"
                }
                }';

                break;
            case 'news':
                $cont = '{
                        "touser":"' . $toUserID . '",
                        "msgtype":"news",
                        "news":{' . $message->get_news() . '}
                    }';
                break;
            default:
                $cont = '{
                "touser": "' . $toUserID . '",
                "msgtype": "text",
                "text": {
                    "content": "' . $content . '"
                }
                }';
        }

        $url="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$公众号accToken;
        $ret = self::curl_post_page($url,$cont);

        if($messageType=='text' || $messageType=='news') {
            self::记录图文和文本发送消息($message,$ret);
        }

        logger()->logInfo("---sendClientMSG result---with #ret:" . $ret);

        return $ret;
    }

    private static function 记录图文和文本发送消息(DoMessage $message,$消息发送结果) {
        $接收消息用户openID = $message->get_to_user_name();
        $公众号信息 = pdo()->selectColumns('用户',array('公众号ID','公众号openID','name'),array('openID'=>$接收消息用户openID));
        if($message->get_message_type()=='news') {
            $type = '图文消息';
            $content = self::返回用户发送图文消息内容($message);
        }else {
            $type = '文本消息';
            $str = $message->get_content();
            $str = str_replace(array("\r\n","\r","\n"),'',$str);
            $content = '{
                "text": {
                    "content": "' . $str . '"
                }
                }';

            $content = json_decode($content);
            $文本内容 = mb_substr($content->text->content,0,20,'utf8');
//            $content = urlencode($文本内容);
            $content = $文本内容;
        }

        $发送结果 =  json_decode($消息发送结果);
        if($发送结果->errcode) {
            $结果  = '否';
        }else {
            $结果  = '是';
        }

        $do = new Do消息发送记录();
        $do -> set_接收消息用户openID($接收消息用户openID);
        $do -> set_消息类型($type);
        $do -> set_发送时间(Date('Y-m-d H:i:s'));
        $do -> set_是否正确发送($结果);
        $do -> set_错误代码($发送结果->errcode);
        $do -> set_消息内容($content);
        $do -> set_公众号ID($公众号信息['公众号ID']);
        $do -> set_公众号openID($公众号信息['公众号openID']);
        $do -> set_name($公众号信息['name']);
        $do -> save();
    }

    private static function 返回用户发送图文消息内容(DoMessage $message) {
        $绑定收银台 = null;
        $用户信息 = pdo()->selectColumns('用户',array('id','上级','店员工','认证'),array('openID'=>$message->get_to_user_name()));
        if($用户信息['店员工']==2) {
            $绑定收银台 = pdo()->selectColumns('用户二维码',array('id'),array('店长id'=>$用户信息['上级'],'当前绑定员工id'=>$用户信息['id']));
        }else if($用户信息['认证']==2) {
            $绑定收银台 = pdo()->selectColumns('用户二维码',array('id'),array('店长id'=>$用户信息['id'],'当前绑定员工id'=>$用户信息['id']));
        }

        $图文消息 = $message->get_news();
        $图文消息json = '{
                        "news":{' . $图文消息 . '}
                    }';
        $图文消息对象 = json_decode($图文消息json);

        if($绑定收银台) {
            return $图文消息对象->news->articles[1]->title;
//            return urlencode($图文消息对象->news->articles[1]->title);
        }else {
            return $图文消息对象->news->articles[0]->title;
//            return urlencode($图文消息对象->news->articles[0]->title);
        }

    }

    private static function fh获取媒体资源media_id(DoMessage $message,$vs公众号id) {
        //先通过A公众号下载媒体文件 再通过B公众号上传媒体文件
        //返回b公众号的媒体文件id
        $公众号id = pdo()->selectColumns('用户',array('公众号ID'),array('openID'=>$message->get_to_user_name()));
        $公众号accToken =  Tools::fh通过公众号id获取公众号Token信息($公众号id['公众号ID']);
        $url = 'https://api.weixin.qq.com/cgi-bin/media/get?access_token='.$公众号accToken.'&media_id='.$message->get_media_id();
        $content = self::downloadWeixinFile($url);
        $filename = "./cache/wxqrcode/".uniqid().time().".amr";
        self::saveWeixinFile($filename, $content["body"]);
        return self::f上传媒体文件返回media_id($filename,$vs公众号id);
    }

    static function f上传媒体文件返回media_id($filename,$vs公众号id) {
        //上传临时素材文件
        $type = "voice";
        $access_token=Tools::fh通过公众号id获取公众号Token信息($vs公众号id);
        $filedata = array("file1"  => "@".$filename);
        $url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=$access_token&type=$type";
        $result = self::curl_post_page($url, $filedata);
        $result = json_decode($result);
        unlink($filename);
        return $result->media_id;
    }

    static function downloadWeixinFile($url)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_NOBODY, 0);    //只取body头
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $package = curl_exec($ch);
        $httpinfo = curl_getinfo($ch);
        curl_close($ch);
        $imageAll = array_merge(array('header' => $httpinfo), array('body' => $package));
        return $imageAll;
    }

    static function saveWeixinFile($filename, $filecontent)
    {
        $local_file = fopen($filename, 'w');
        if (false !== $local_file){
            if (false !== fwrite($local_file, $filecontent)) {
                fclose($local_file);
            }
        }
    }

    //todo 多收银台22
    static function curl_post_page($url, $data, $timeout = 4)
    {
//        var_dump($url,$data);
//        $data = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": a1123}}}';
//        $data = 123;
//        var_dump($data);
////        $url = "http://localhost/aaa.php";
//        $ch = curl_init();
//        curl_setopt($ch, CURLOPT_URL, $url);
//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
//        // post数据
//        curl_setopt($ch, CURLOPT_POST, 1);
//        // post的变量
//        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
//
//        $output = curl_exec($ch);
//        var_dump($output);die;
//        curl_close($ch);

        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_CUSTOMREQUEST,"POST");
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
        curl_setopt($ch,CURLOPT_AUTOREFERER,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        $output = curl_exec($ch);
        if(curl_errno($ch)){
            echo curl_error($ch);
        }
        return $output;
    }

}
